package com.app.android.coliy.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.app.android.coliy.MyApplication;
import com.app.android.coliy.tool.CommToast;
import com.app.android.coliy.tool.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/6/12.
 */

public class Util {


    public static byte[] hexToByte(String var0) {
        if (var0.length() <= 0) {
            return new byte[0];
        } else {
            if ((var0 = var0.replace(" ", "")).length() % 2 == 1) {
                StringBuffer var10000 = new StringBuffer(var0);
                var10000.insert(var0.length() - 1, '0');
                var0 = var10000.toString();
            }

            byte[] var1 = new byte[var0.length() / 2];

            int var3;
            for(int var2 = 0; var2 < var0.length(); var2 = var3) {
                String var4 = var0.substring(var2, var3 = var2 + 2);
                if (var2 == 0) {
                    var1[var2] = (byte)Integer.parseInt(var4, 16);
                } else {
                    var1[var2 / 2] = (byte)Integer.parseInt(var4, 16);
                }
            }

            return var1;
        }
    }


    public static void closeApp() {
//        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    //数字显示处理，保留几位小数点   length: 几位小数点
    public static String numDecimalFormat(String num, int length) {
        try {
            String decimalStr = "0";
            if (length > 0) {
                decimalStr += ".";
                for (int i = 0; i < length; i++) {
                    decimalStr += "0";
                }
            }
            DecimalFormat format = new DecimalFormat(decimalStr);
            String a = format.format(new BigDecimal(num));
            return a;
        } catch (Exception e) {
            return num;
        }
    }

    public static byte[] buildPacket(byte[] imageData, int imgHeight) {
        byte[] bytes = new byte[12 + imageData.length];   // 发送数据总长度为header 12字节 + png数据长度

        Log.i("imageData:"+ imageData.length + " bytes:"+ bytes.length);

        //头部数据
        byte[] head1 = intToByte(imageData.length);   //图片数据长度
        byte[] head2 = intToByte(0x88);
        byte[] head3 = intToByte(imgHeight);            //图片长度

        //组包  头部
        System.arraycopy(head1, 0, bytes, 0, 4);
        System.arraycopy(head2, 0, bytes, 4, 4);
        System.arraycopy(head3, 0, bytes, 8, 4);

        //组包  图像
        System.arraycopy(imageData, 0, bytes, 12, imageData.length);
        return bytes;    // 返回的就是组好包的 byte [], 通过FscBleCentralApi的send接口发送出去
    }

//    public static byte[] buildPacket(byte[] imageData, int imgHeight) {
//        byte[] bytes = new byte[12 + imageData.length];   // 发送数据总长度为header 12字节 + png数据长度
//
//        Log.i("imageData:"+ imageData.length + " bytes:"+ bytes.length);
//
//        //头部数据
//        byte[] head1 = intToByte(imageData.length);   //图片数据长度
//        byte[] head2 = intToByte(0x88);
//        byte[] head3 = intToByte(imgHeight);            //图片长度
//
//        //组包  头部
//        System.arraycopy(head1, 0, bytes, 0, 4);
//        System.arraycopy(head2, 0, bytes, 4, 4);
//        System.arraycopy(head3, 0, bytes, 8, 4);
//
//        //组包  图像
//        System.arraycopy(imageData, 0, bytes, 12, imageData.length);
//        return bytes;    // 返回的就是组好包的 byte [], 通过FscBleCentralApi的send接口发送出去
//    }

    //生成握手包
    public static byte[] buildPacket_First(byte[] imageData, int imgHeight) {
        byte[] bytes = new byte[16];   // 发送数据总长度为header 12字节 + png数据长度

        Log.i("imageData:"+ imageData.length + " bytes:"+ bytes.length);

        //头部数据
        byte[] head0 = {(byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80};
        byte[] head1 = intToByte(imageData.length);   //图片数据长度
        byte[] head2 = intToByte(0x88);
        byte[] head3 = intToByte(imgHeight);            //图片长度

        //组包  头部
        System.arraycopy(head0, 0, bytes, 0, 4);
        System.arraycopy(head1, 0, bytes, 4, 4);
        System.arraycopy(head2, 0, bytes, 8, 4);
        System.arraycopy(head3, 0, bytes, 12, 4);

        return bytes;    // 返回的就是组好包的 byte [], 通过FscBleCentralApi的send接口发送出去
    }

















    public static byte[] intToByte(int i) {
        byte[] result = new byte[4];
        // 由高位到低位
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }


    public static String getSerialNumber(int serialNumber) {
        String str = "";
        if (serialNumber < 10) {
            str = "00" + serialNumber;
        } else if (serialNumber < 100) {
            str = "0" + serialNumber;
        } else {
            str = "" + serialNumber;
        }
        return str;
    }

    public static String getString(int id) {
        return MyApplication.getTopAct().getResources().getString(id);
    }

    public static String toHexEncoding(int color) {
        String R, G, B;
        StringBuffer sb = new StringBuffer();
        R = Integer.toHexString(Color.red(color));
        G = Integer.toHexString(Color.green(color));
        B = Integer.toHexString(Color.blue(color));
        //判断获取到的R,G,B值的长度 如果长度等于1 给R,G,B值的前边添0
        R = R.length() == 1 ? "0" + R : R;
        G = G.length() == 1 ? "0" + G : G;
        B = B.length() == 1 ? "0" + B : B;
        sb.append("#");
        sb.append(R);
        sb.append(G);
        sb.append(B);
        return sb.toString();
    }


    public static boolean isWifi(Context context) {
        if (getNetworkClass(context) == ConnectivityManager.TYPE_WIFI) {
            return true;
        } else {
            return false;
        }
    }

    private static int getNetworkClass(Context context) {
        int networkType = ConnectivityManager.TYPE_MOBILE;
        try {
            final NetworkInfo network = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (network != null && network.isAvailable() && network.isConnected()) {
                int type = network.getType();
                if (type == ConnectivityManager.TYPE_WIFI) {
                    networkType = ConnectivityManager.TYPE_WIFI;
                } else if (type == ConnectivityManager.TYPE_MOBILE) {
                    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                    networkType = telephonyManager.getNetworkType();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Log.i("networkType:" + networkType);
        return networkType;
    }


    //万 级转换
    public static String numberFormat(int num) {
        String numStr = num + "";
        if (num >= 10000) {
            DecimalFormat format = new DecimalFormat("0.0");
            numStr = format.format(num / 10000) + "万";
        }
        return numStr;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {

        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        System.out.println("Drawable转Bitmap");
        Bitmap.Config config =
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        //注意，下面三行代码要用到，否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void copy(Context context, String msg, boolean... ishowTost) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("code", msg);
        clipboard.setPrimaryClip(clip);
        if (ishowTost.length > 0 && (boolean) ishowTost[0]) {
            CommToast.showToast(context, "已复制");
        }
    }

    /**
     * 获取手机大小（分辨率）
     */
    public static DisplayMetrics getScreenPix(Activity activity) {
        DisplayMetrics displaysMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displaysMetrics);
        return displaysMetrics;
    }

    /**
     * 判断SDCard是否可用
     */
    public static boolean existSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    // 获取手机状态栏高度
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    public static List<PackageInfo> getAppList(Context context) {
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
        // 判断是否系统应用：
        List<PackageInfo> apps = new ArrayList<PackageInfo>();
        for (int i = 0; i < packageInfoList.size(); i++) {
            PackageInfo pak = (PackageInfo) packageInfoList.get(i);
            //判断是否为系统预装的应用
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
                // 第三方应用
                apps.add(pak);
            } else {
                //系统应用
            }
        }
        return apps;
    }

    //启动一个app
    public static void startAPP(Context context, String appPackageName) {
        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
            context.startActivity(intent);
        } catch (Exception e) {
            CommToast.showToast(context, "没有安装");
        }
    }


    /**
     * 设置键盘展现和关闭
     *
     * @param bShow
     * @param context
     * @param view
     */
    public static void showKeyBoard(boolean bShow, Context context, View view) {
        if (bShow) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        } else {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    /**
     * 获取app的根目录
     *
     * @return 文件缓存根路径
     */
    public static String getDiskCacheRootDir(Context context) {
        File diskRootFile;
        if (existsSdcard()) {
            diskRootFile = context.getExternalCacheDir();
        } else {
            diskRootFile = context.getCacheDir();
        }
        String cachePath = "";
        if (diskRootFile != null) {
            cachePath = diskRootFile.getPath();
        } else {
            throw new IllegalArgumentException("disk is invalid");
        }
        return cachePath;
    }

    //获取app的文件根路径
    public static String getDiskFileRootDir(Context context) {
        File diskRootFile;
        if (existsSdcard()) {
            diskRootFile = context.getExternalFilesDir(null);
        } else {
            diskRootFile = context.getFilesDir();
        }
        String filePath = "";
        if (diskRootFile != null) {
            filePath = diskRootFile.getPath();
        } else {
            throw new IllegalArgumentException("disk is invalid");
        }
        return filePath;
    }

    /**
     * 判断外置sdcard是否可以正常使用
     *
     * @return
     */
    public static Boolean existsSdcard() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable();
    }

    //手机号检查
    public static boolean isChinaPhoneLegal(String str) {
        String regExp = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }


    /**
     * 获取版本号名称
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取版本号code
     *
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //通过反射获取类的属性和属性值
    public static Map<String, String> getFieldMap(Object object) {
        Map<String, String> map = new HashMap<>();
        Field fields[] = object.getClass().getDeclaredFields();//cHis 是实体类名称
        try {
            Field.setAccessible(fields, true);
            for (int i = 0; i < fields.length; i++) {
                String name = fields[i].getName();
                String value = "";
                if (fields[i].get(object) != null) {
                    value = fields[i].get(object).toString();
                }
                map.put(name, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    public static File uri2File(Context context, Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = context.getContentResolver().query(uri, proj, null, null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    //压缩图片
    public static File compressImageToFile(File file, String filename) {
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        if (bitmap == null) {
            return null;
        }
        // 0-100 100为不压缩
        int options = 50;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        try {
            File temp_file = new File(Util.getDiskFileRootDir(MyApplication.context), filename);
            FileOutputStream fos = new FileOutputStream(temp_file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
            return temp_file;
        } catch (Exception e) {
            e.printStackTrace();
            return file;
        }
    }

}
